package com.wekri.wechat4j.api.marketing;

import com.wekri.wechat4j.api.marketing.bean.RedPackBean;
import com.wekri.wechat4j.api.marketing.bean.RedPackInfo;
import com.wekri.wechat4j.api.marketing.bean.RedPackResult;
import com.wekri.wechat4j.api.pay.WeChatPayConfig;
import com.wekri.wechat4j.api.pay.WeChatPayUtil;
import com.wekri.wechat4j.util.Cert;
import com.wekri.wechat4j.util.HttpUtils;
import com.wekri.wechat4j.util.XmlUtil;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * 现金红包API
 *
 * @author liuweiguo
 * @date 2019/6/14.
 */
public class RedPackApi {
    /**
     * 发放现金红包
     * 请求方式：POST 需要证书
     */
    private static final String POST_SEND_RED_PACK = "https://api.mch.weixin.qq.com/mmpaymkttransfers/sendredpack";
    /**
     * 发放裂变红包
     * 请求方式：POST 需要证书
     */
    private static final String POST_SEND_GROUP_RED_PACK = "https://api.mch.weixin.qq.com/mmpaymkttransfers/sendgroupredpack";

    /**
     * 用于商户对已发放的红包进行查询红包的具体信息，可支持普通红包和裂变包。
     * 请求方式	POST 需要证书
     */
    private static final String POST_RED_PACK_INFO = "https://api.mch.weixin.qq.com/mmpaymkttransfers/gethbinfo";

    /**
     * 发送普通红包
     *
     * @param bean
     * @param cert 证书
     * @return
     */
    public RedPackResult send(RedPackBean bean, Cert cert) {
        return XmlUtil.parseObject(HttpUtils.postXmlWithCert(POST_SEND_RED_PACK, XmlUtil.toXmlStr(bean), cert),
                RedPackResult.class);
    }

    /**
     * 查询红包记录
     *
     * @param billNo    商户订单号
     * @param payConfig 支付配置
     * @return
     * @throws Exception
     */
    public RedPackInfo redPackInfo(String billNo, WeChatPayConfig payConfig) throws Exception {
        Map<String, String> map = new HashMap<>();
        map.put("mch_id", payConfig.getMchID());
        map.put("appid", payConfig.getAppID());
        map.put("mch_billno", billNo);
        map.put("nonce_str", UUID.randomUUID().toString().replace("-", ""));
        map.put("bill_type", "MCHT");
        map.put("sign", WeChatPayUtil.generateSignature(map, payConfig.getKey()));
        return XmlUtil.parseObject(HttpUtils.postXmlWithCert(POST_RED_PACK_INFO, WeChatPayUtil.mapToXml(map), new Cert(payConfig.getCertStream(), payConfig.getMchID())),
                RedPackInfo.class);
    }

    public String generateBillNo() {
        String date = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmssSSS"));
        return date + String.valueOf(Math.random()).substring(2, 13);
    }
}
